//
//  TradeBuyOutViewController.m
//  Item
//
//  Created by 刘炳举 on 12/18/15.
//  Copyright © 2015 Kelly. All rights reserved.
//

#import "TradeBuyOutViewController.h"
#import "CustomTableViewCell.h"
#import "AutocompletionTableView.h"
#import "FlashDataTableViewController.h"
#import "tools.h"
#import "DropDownListView.h"
#define URL @"http://a.apix.cn/apixmoney/stockdata/stock?stockid"
@interface TradeBuyOutViewController (){
    NSUserDefaults *user;
    NSMutableArray* sharesCodeArray;
    NSString* filePath ;
}
@property (strong,nonatomic)FlashDataTableViewController* flashData;
@property (retain, nonatomic) IBOutlet UILabel *topStopPrice;
@property (retain, nonatomic) IBOutlet UILabel *downStopPrice;
@property (retain, nonatomic) IBOutlet UIButton *cutPrice;
@property (retain, nonatomic) IBOutlet UIButton *addPrice;
@property (retain, nonatomic) IBOutlet UIButton *cutCount;
@property (retain, nonatomic) IBOutlet UIButton *addCount;
@property (retain, nonatomic) IBOutlet UITextField *currPrice;
@property (retain, nonatomic) IBOutlet UILabel *couldbuy;
@property (retain, nonatomic) IBOutlet UITextField *buyCount;
@property (retain, nonatomic) IBOutlet UITableView *tabBuyOut;
@property (retain, nonatomic) IBOutlet UILabel *account;
@property (retain, nonatomic) IBOutlet UITableView *tabBuyIn;
@property (retain, nonatomic) IBOutlet UILabel *uName;
@property (nonatomic, strong) NSArray *nameArr;
@property (nonatomic, strong) NSArray *nameArr2;
@property (nonatomic, strong) NSMutableArray *BuyPriceArr;
@property (nonatomic, strong) NSMutableArray *SellPriceArr;
@property (nonatomic, strong) NSMutableArray *BuyCountArr;
@property (nonatomic, strong) NSMutableArray *SellCountArr;
@property (nonatomic, strong) AutocompletionTableView *autoCompleter;
@property (retain, nonatomic) IBOutlet UIButton *changeCountTwo;
@property (retain, nonatomic) IBOutlet UIButton *changeCountThree;
@property (retain, nonatomic) IBOutlet UIButton *changeCountFour;
@end

@implementation TradeBuyOutViewController{
    NSArray *sharesType;
    NSMutableArray* chosseArray;
}

@synthesize btnSelect;

-(AutocompletionTableView*)autoCompleter{
    if (!_autoCompleter) {
        _autoCompleter = [[AutocompletionTableView alloc] initWithTextField:self.searchField inViewController:self withOptions:nil];
        _autoCompleter.autoCompleteDelegate = self;
        /*
         get sharesCode from plist AllSharesCode.plist
         */
        filePath = [tools returnPlistPath];
        sharesCodeArray = [NSMutableArray arrayWithContentsOfFile:filePath];
        self.sharesArray = sharesCodeArray;
    }
    return _autoCompleter;
}





- (void)viewDidLoad {
    [super viewDidLoad];
    [self initSharesType];
    [self initData];
    self.navigationController.navigationBar.topItem.title =@"交易卖出";
    [self.searchField addTarget:self.autoCompleter action:@selector(textFieldValueChanged:) forControlEvents:UIControlEventEditingChanged];
}


-(void)viewWillDisappear:(BOOL)animated{
    if (_timer) {
        dispatch_cancel(_timer);
        _timer= nil;
    };
}
-(void)initSharesType{
    btnSelect.layer.borderWidth = 1;
    btnSelect.layer.borderColor = [[UIColor grayColor] CGColor];
}

-(void)initData{
    user = [NSUserDefaults standardUserDefaults];
    _account.text = [user objectForKey:@"currentAcc"];
    _account.font = [UIFont systemFontOfSize:12.0f];
    self.nameArr = [NSArray arrayWithObjects:@"卖五",@"卖四",@"卖三",@"卖二",@"卖一", nil];
    self.nameArr2 =[NSArray arrayWithObjects:@"买五",@"买四",@"买三",@"买二",@"买一", nil];
    _searchField.font = [UIFont systemFontOfSize:12.0f];
    [self getDataRep];
    
    NSString* currCode = [user objectForKey:@"currentCode"];
    if (currCode) {
        
        _currCode = [tools changeStr:currCode];
        [self request:URL withHttpArg:_currCode];
    }else{
        _currCode = nil;
    }
    _currPrice.textAlignment = NSTextAlignmentCenter;
    _buyCount.textAlignment = NSTextAlignmentCenter;
    /********************btnclicked*************/
    
    [_addPrice setTag:1001];
    [_cutPrice setTag:1002];
    [_addCount setTag:1003];
    [_cutCount setTag:1004];
    
    [_addPrice addTarget:self action:@selector(btncall:) forControlEvents:UIControlEventTouchUpInside];
    [_cutPrice addTarget:self action:@selector(btncall:) forControlEvents:UIControlEventTouchUpInside];
    [_addCount addTarget:self action:@selector(btncall:) forControlEvents:UIControlEventTouchUpInside];
    [_cutCount addTarget:self action:@selector(btncall:) forControlEvents:UIControlEventTouchUpInside];

    [_changeCountTwo setTag:1005];
    [_changeCountThree setTag:1006];
    [_changeCountFour setTag:1007];
    
    [_changeCountTwo addTarget:self action:@selector(btncall:) forControlEvents:UIControlEventTouchUpInside];
    [_changeCountThree addTarget:self action:@selector(btncall:) forControlEvents:UIControlEventTouchUpInside];
    [_changeCountFour addTarget:self action:@selector(btncall:) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    /********************DropDown***************/
    chosseArray = [[NSMutableArray arrayWithArray:@[
                                                    @[@"s:99102-075",@"222",@"333"]
                                                    ]] retain];
    DropDownListView* dropDownView = [[DropDownListView alloc]initWithFrame:CGRectMake(_searchField.frame.origin.x, _searchField.frame.origin.y - 10, _searchField.frame.size.width, _searchField.frame.size.height) dataSource:self delegate:self];
    dropDownView.mSuperView = self.view;
    [self.view addSubview:dropDownView];

    
}

#pragma mark -dropMenu
-(void)chooseAtSection:(NSInteger)section index:(NSInteger)index{
    NSLog(@"%@",chosseArray[section][index]);
    [user setObject:chosseArray[section][index] forKey:@"currentAcc"];
}

-(NSInteger)numberOfSections{
    return 1;
}

-(NSInteger)numberOfRowsInSection:(NSInteger)section{
    NSArray* array = chosseArray[section];
    return [array count];
}

-(NSString *)titleInSection:(NSInteger)section index:(NSInteger)index{
    return chosseArray[section][index];
}
-(NSInteger)defaultShowSection:(NSInteger)section{
    return 0;
}

#pragma -mark button clicked
- (IBAction)sellOut {
}

-(void)btncall:(UIButton*)btn{
    NSInteger tag = btn.tag;
    switch (tag) {
        case 1001:
            NSLog(@"%ld",(long)tag);
            if (![_currPrice.text isEqualToString:@""]) {
                _currPrice.text = [tools changePrice:_currPrice.text addStr:0.01f type:@"ADD"];
                _currPrice.textColor = [UIColor redColor];
            }
            break;
        case 1002:
            if (![_currPrice.text isEqualToString:@""]) {
                _currPrice.text =[tools changePrice:_currPrice.text addStr:0.01f type:@"CUT"];
                _currPrice.textColor = [UIColor greenColor];
            }
            break;
        case 1003:
            if (![_buyCount.text isEqualToString:@""]) {
                _buyCount.text = [tools changeCount:_buyCount.text addStr:1 type:@"ADD"];
                _buyCount.textColor = [UIColor redColor];
            }
            break;
        case 1004:
            if (![_buyCount.text isEqualToString:@""]) {
                _buyCount.text = [tools changeCount:_buyCount.text addStr:1 type:@"CUT"];
                _buyCount.textColor = [UIColor greenColor];
            }
            break;
        case 1005:
            NSLog(@"1005");
            if (![_couldbuy.text isEqualToString:@""]) {
                _buyCount.text = [tools changeCount:_couldbuy.text addStr:2 type:@"/"];
            }
            break;
        case 1006:
            NSLog(@"1006");
            if (![_couldbuy.text isEqualToString:@""]) {
                _buyCount.text = [tools changeCount:_couldbuy.text addStr:3 type:@"/"];
            }
            break;
        case 1007:
            NSLog(@"1007");
            if (![_couldbuy.text isEqualToString:@""]) {
                _buyCount.text = [tools changeCount:_couldbuy.text addStr:4 type:@"/"];
            }
            break;

        default:
            break;
    }

}

#pragma -mark dropMenu
#pragma -mark AutocompletionTableViewDelegate
-(NSArray*) autoCompletion:(AutocompletionTableView *)completer{
    return self.sharesArray;
}
-(void)autoCompletion:(AutocompletionTableView *)completer didSelectAutoCompleteSuggestionWithIndex:(NSInteger)index{
    if ([_searchField.text length] > 6) {
        NSString* codeStr = [self.searchField.text substringToIndex:6];
        
        _currCode = [tools changeStr:codeStr];
        [self request:URL withHttpArg:_currCode];
    }else{
        _searchField.text = @"";
    }
}
#pragma  -mark getDat from Inter
-(void)request:(NSString*)httpUrl withHttpArg:(NSString*)httpArg{
    NSDictionary *headers = @{ @"accept": @"application/json",
                               @"content-type": @"application/json",
                               @"apix-key": @"52d8748baf0345b97f8efe6ae06fe5be" };
    NSString* urlStr = [[NSString alloc] initWithFormat:@"%@=%@",httpUrl,httpArg];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL* url = [NSURL URLWithString:urlStr];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                               cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                           timeoutInterval:10.0];
        [request setHTTPMethod:@"GET"];
        [request setAllHTTPHeaderFields:headers];
        
        NSURLSession *session = [NSURLSession sharedSession];
        NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
                                                    completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                        if (error) {
                                                            NSLog(@"%@", error);
                                                        } else {
                                                            
                                                            NSDictionary* codeMsg = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
                                                            [self getSharesData:codeMsg];
                                                        }
                                                    }];
        [dataTask resume];
    });
}

-(void)getDataRep{
    NSTimeInterval period = 30.0;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), period * NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(_timer, ^{
        [self repeatRequest];
    });
    dispatch_resume(_timer);
    
}

-(void)repeatRequest{
    NSString* str;
    if (self.searchField.text.length > 5 ){
        str =  [tools changeStr:[self.searchField.text substringToIndex:6]];
        [self request:URL withHttpArg:str];
    }else return;
}

#pragma -mark flash data
-(void)getSharesData:(NSDictionary*)dict{
    NSDictionary* infoDic =[[dict objectForKey:@"data"] objectForKey:@"stockinfo"];
    NSLog(@"infoDic:%@",infoDic);
    if (infoDic == nil) return;
    _BuyPriceArr = [[NSMutableArray arrayWithCapacity:5] retain];
    [_BuyPriceArr addObject:[infoDic objectForKey:@"buyFivePrice"]];
    [_BuyPriceArr addObject:[infoDic objectForKey:@"buyFourPrice"]];
    [_BuyPriceArr addObject:[infoDic objectForKey:@"buyThreePrice"]];
    [_BuyPriceArr addObject:[infoDic objectForKey:@"buyTwoPrice"]];
    [_BuyPriceArr addObject:[infoDic objectForKey:@"buyOnePrice"]];
    
    _BuyCountArr = [[NSMutableArray arrayWithCapacity:5] retain];
    [_BuyCountArr addObject:[infoDic objectForKey:@"buyFive"]];
    [_BuyCountArr addObject:[infoDic objectForKey:@"buyFour"]];
    [_BuyCountArr addObject:[infoDic objectForKey:@"buyThree"]];
    [_BuyCountArr addObject:[infoDic objectForKey:@"buyTwo"]];
    [_BuyCountArr addObject:[infoDic objectForKey:@"buyOne"]];
    
    _SellPriceArr = [[NSMutableArray arrayWithCapacity:5] retain];
    [_SellPriceArr addObject:[infoDic objectForKey:@"sellFivePrice"]];
    [_SellPriceArr addObject:[infoDic objectForKey:@"sellFourPrice"]];
    [_SellPriceArr addObject:[infoDic objectForKey:@"sellThreePrice"]];
    [_SellPriceArr addObject:[infoDic objectForKey:@"sellTwoPrice"]];
    [_SellPriceArr addObject:[infoDic objectForKey:@"sellOnePrice"]];
    
    _SellCountArr = [[NSMutableArray arrayWithCapacity:5] retain];
    [_SellCountArr addObject:[infoDic objectForKey:@"sellFive"]];
    [_SellCountArr addObject:[infoDic objectForKey:@"sellFour"]];
    [_SellCountArr addObject:[infoDic objectForKey:@"sellThree"]];
    [_SellCountArr addObject:[infoDic objectForKey:@"sellTwo"]];
    [_SellCountArr addObject:[infoDic objectForKey:@"sellOne"]];
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [_currPrice setText:[tools floatToStr:[NSString stringWithFormat:@"%@",[infoDic objectForKey:@"currentPrice"]] ]];
             
//            [_buyCount setText:[NSString stringWithFormat:@"%@",[infoDic objectForKey:@"totalNumber"]]];
//            _buyCount.textColor = [UIColor blackColor];
            _currPrice.textColor = [UIColor blackColor];
            //设置涨停价与跌停价
            [_topStopPrice setText:[tools returnUPOrDownStopPrice:[NSString stringWithFormat:@"%@",[infoDic objectForKey:@"closingPrice"]] type:@"UP"]];
            [_downStopPrice setText:[tools returnUPOrDownStopPrice:[NSString stringWithFormat:@"%@",[infoDic objectForKey:@"closingPrice"]] type:@"DOWN"]];

            
            
            [_tabBuyIn reloadData];
            [_tabBuyOut reloadData];
            
        });
    });
}
#pragma  -mark table delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([tableView isEqual:_tabBuyIn]) {
        return [_nameArr count];
    } else {
        return [_nameArr2 count];;
    }
    return 1;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([tableView isEqual:_tabBuyIn]) {
        return [self loadTable:_tabBuyIn cellForRowAtIndexPath:indexPath] ;
    } else if([tableView isEqual:_tabBuyOut]){
        return [self loadTable:_tabBuyOut cellForRowAtIndexPath:indexPath] ;
    }
    return nil;
}

-(UITableViewCell *)loadTable:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier =@"CustomCell";
    
    UINib *nib = [UINib nibWithNibName:@"CustomTableViewCell" bundle:nil];
    [tableView registerNib:nib forCellReuseIdentifier:cellIdentifier];
    tableView.separatorStyle = NO;
    tableView.scrollEnabled =NO;
    CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[[CustomTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]autorelease];
    }
    NSUInteger row = [indexPath row];
    if ([tableView isEqual:_tabBuyIn]) {
        cell.sName = [self.nameArr2 objectAtIndex:row];
        if ([_BuyCountArr count] > 0) {
            NSString* newp = [NSString stringWithFormat:@"%@",[_BuyPriceArr objectAtIndex:row]];
            cell.sPrice = [tools floatToStr:newp];
            if ([tools comparePrice:_currPrice.text newNum:newp] == YES) {
                cell.price.textColor = [UIColor redColor];
            }else{
                cell.price.textColor = [UIColor greenColor];
            }
            cell.sCount = [tools changeString:[_BuyCountArr objectAtIndex:row]];
        }else{
            cell.sPrice = @"--";
            cell.price.textColor = [UIColor blackColor];
            cell.sCount = @"--";
        }

    } else if([tableView isEqual:_tabBuyOut]){
        cell.sName = [self.nameArr objectAtIndex:row];
        if ([_SellCountArr count] > 0) {
            NSString* newp = [NSString stringWithFormat:@"%@",[_SellPriceArr objectAtIndex:row]];
            cell.sPrice = [tools floatToStr:newp];
            if ([tools comparePrice:_currPrice.text newNum:newp]  == YES ) {
                cell.price.textColor = [UIColor redColor];
            }else{
                cell.price.textColor = [UIColor greenColor];
            }
            
            cell.sCount =[tools changeString:[_SellCountArr objectAtIndex:row]];
        }else{
            cell.sPrice = @"--";
            cell.price.textColor = [UIColor blackColor];
            cell.sCount = @"--";
        }

    }
    return cell;
}

-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation{
    return (toInterfaceOrientation == UIInterfaceOrientationMaskPortrait);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [_tabBuyOut release];
    [_tabBuyIn release];
    [_uName release];
    [_account release];
    [btnSelect release];
    [_searchField release];
    [_currPrice release];
    [_buyCount release];
    [_cutPrice release];
    [_addPrice release];
    [_cutCount release];
    [_addCount release];
    [_topStopPrice release];
    [_downStopPrice release];
    [_changeCountTwo release];
    [_changeCountThree release];
    [_changeCountFour release];
    [super dealloc];
}

- (IBAction)View_TouchDown:(id)sender {
    [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"TradeSell"]) {
        if ([segue.destinationViewController isKindOfClass:[FlashDataTableViewController class]]) {
            self.flashData = (FlashDataTableViewController*)segue.destinationViewController;
        }
    }
    
}
@end
